package com.accgm.api.common;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.FormTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.accgm.api.utils.LogUtils;

public class WebUtils
{

	public static String getResponseHtml( HttpResponse response )
	{
		HttpEntity entity = response.getEntity();
		
		StringBuffer sb = new StringBuffer();
		String lineString;
		try
		{
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(entity.getContent()));
			
			lineString = bufferReader.readLine();
		
			while (lineString != null)
			{
				sb.append(lineString);sb.append("\n");
				//LogUtils.log.info(lineString);
				lineString = bufferReader.readLine();
			}
			bufferReader.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		 
        return sb.toString();
	}
	
	public static String getResponseHtml( HttpResponse response , String charset)
	{
        HttpEntity entity = response.getEntity();
		
		StringBuffer sb = new StringBuffer();
		String lineString;
		try
		{
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(entity.getContent(),charset));
			
			lineString = bufferReader.readLine();
		
			while (lineString != null)
			{
				sb.append(lineString);sb.append("\n");
				lineString = bufferReader.readLine();
			}
			bufferReader.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		 
        return sb.toString();
	}
	
	public static InputStream getResponseStream( HttpResponse response )
	{
		HttpEntity entity = response.getEntity();
		 
		try
		{
			return entity.getContent();
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		} 	 
		 
	}
	
	
	

	
	
	public static HttpPost getFormPost( WebForm form )
	{
		List<NameValuePair> paramList = form.getParamsList();
		
		HttpPost httpost =  new HttpPost( form.getActionPath() );
		try
		{   
			httpost.setEntity(new UrlEncodedFormEntity(paramList,form.getCharset()));
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		
		return httpost;
	}
	
	public static HttpPost getFormPost(String basePath, WebForm form )
	{
		List<NameValuePair> paramList = form.getParamsList();
		
		HttpPost httpost =  new HttpPost(basePath + form.getActionPath() );
		try
		{
			httpost.setEntity(new UrlEncodedFormEntity(paramList,form.getCharset()));
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		
		return httpost;
	}
	
	/**
	 * 鍙栫綉椤佃〃鍗�
	 * 
	 * @param content
	 * @return
	 * @throws LocalServerException
	 */
	public static WebForm getPageForm(HttpGet inputGet, String html)
	{
		String charset = getHTMLCharSet( html );
		Parser parser = Parser.createParser(html, charset);
		NodeList nodeList = null;
	 
		FormTag formTag = null;
		try
		{
			nodeList = parser.parse(new NodeClassFilter(FormTag.class));

			formTag = (FormTag) nodeList.elementAt(0);
		} 
		catch (ParserException e)
		{
			e.printStackTrace();
		}

		if (formTag == null)
		{
			LogUtils.log.info("ss");
			return null;
		}
		return new WebForm(formTag, inputGet.getURI(), charset);
	}
	
	
	/**
	 * 鍙栫綉椤佃〃鍗�
	 * 
	 * @param content
	 * @return
	 * @throws LocalServerException
	 */
	public static WebForm getPageForm(HttpGet inputGet, String html,String charset)
	{
		//String charset = getHTMLCharSet( html );
		Parser parser = Parser.createParser(html, charset);
		NodeList nodeList = null;
	 
		FormTag formTag = null;
		try
		{
			nodeList = parser.parse(new NodeClassFilter(FormTag.class));

			formTag = (FormTag) nodeList.elementAt(0);
		} 
		catch (ParserException e)
		{
			e.printStackTrace();
		}

		if (formTag == null)
		{
			LogUtils.log.info("");
			return null;
		}
		return new WebForm(formTag, inputGet.getURI(), charset);
	}
	
	
	/**
	 * 鎻愬彇琛ㄥ崟
	 * @param inputGet
	 * @param html
	 * @param formIndex 琛ㄥ崟搴忓彿 (浠�寮�)
	 * @return
	 */
	public static WebForm getPageForm(HttpGet inputGet, String html, int formIndex)
	{
		String charset = getHTMLCharSet( html );
		Parser parser = Parser.createParser(html, charset);
		NodeList nodeList = null;
	 
		FormTag formTag = null;
		try
		{
			nodeList = parser.parse(new NodeClassFilter(FormTag.class));
            
			if( formIndex > nodeList.size())
			{
				LogUtils.log.info("form index out of bound:"+formIndex);
				return null;
			}
			
			formTag = (FormTag) nodeList.elementAt( formIndex-1 );
		} 
		catch (ParserException e)
		{
			e.printStackTrace();
		}

		if (formTag == null)
		{
			LogUtils.log.info("");
			return null;
		}
		return new WebForm(formTag, inputGet.getURI(), charset);
	}
	
	
	/**
	 * 鍙栧緱缃戦〉鐨刢harset
	 * @param html
	 * @return
	 */
	public static String getHTMLCharSet( String html )
	{
		Pattern pattern = Pattern.compile("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=(.+?)\" />");
		Matcher m = pattern.matcher( html ); 
		if( m.find() )
		{	
           return m.group(1);
		}
		
		return "gb2312";
	}
	
	public static String getSid( String url )
	{
		String str = url.substring( url.indexOf("sid=") );
		
		int i = str.indexOf('&');
		if( i > 0 )
		{
			str = str.substring(0, i);
		}
		
		return str;
	}
	
	public static String getBasePath( String url )
	{
		Pattern pattern = Pattern.compile("^(http://.+?)/");
		
		Matcher m = pattern.matcher( url ); 
		if( m.find() )
		{	
           return m.group(1);
		}
		
		return "";
	}
	
	/**
	 * 鍙栧緱鐧惧害鐢ㄦ埛鐨勭┖闂村悗缂�悕
	 * @param html
	 * @return
	 */
	public static String getSpaceName( String html )
	{

		Pattern pattern = Pattern.compile("<a href='/(.+?)' target='_blank'>鎴戠殑绌洪棿</a>");
		Matcher m = pattern.matcher( html ); 
		if( m.find() )
		{	
           return m.group(1);
		}
		
		return "";
	}
	
	
	/**
	 * 鍒ゆ柇鐢ㄦ埛鏄惁鍙戣〃鎴愬姛
	 * @param html
	 * @return
	 */
	public static boolean jugeSendSuccess( String html,String matchString )
	{

		Pattern pattern = Pattern.compile(matchString);
		Matcher m = pattern.matcher( html ); 
		if( m.find() )
		{	
           return true;
		}
		
		return false;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		LogUtils.log.info( getHTMLCharSet("<head id=\"ctl00_Head1\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><meta http-equiv=\"Content-Language\" content=\"zh-CN\" /><meta content=\"all\" name=\"robots\" />") );

		 
	}

}
